package com.atguigu.juc.threadLocal;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @author yfstart
 * @create 2022-07-25 17:16
 */
public class DateUtilsDemo {
    public static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    // 解决方式一：synchronized
    public synchronized static Date parseDate(String stringDate) throws Exception {
        return sdf.parse(stringDate);
    }

    // 解决方式二：ThreadLocal
    public static final ThreadLocal<SimpleDateFormat> sdfThreadLocal = ThreadLocal.withInitial(
            () -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

    public static final Date parseByThreadLocal(String stringDate) throws ParseException {
        return sdfThreadLocal.get().parse(stringDate);
    }

    // 解决方法四：DateTimeFormatter 代替 SimpleDateFormat
    public static final DateTimeFormatter DATE_TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public static String format(LocalDateTime localDateTime) {
        return DATE_TIME_FORMAT.format(localDateTime);
    }

    public static LocalDateTime parse(String dateString) {
        return LocalDateTime.parse(dateString, DATE_TIME_FORMAT);
    }

    public static void main(String[] args) throws Exception {
        // sdfByNew();
        // sdfByThreadLocal();
        dateTimeFormatter();
    }

    private static void dateTimeFormatter() {
        for (int i = 1; i <= 5; i++) {
            new Thread(() -> {
                try {
                    System.out.println(DateUtilsDemo.format(DateUtilsDemo.parse("2022-06-01 11:11:11")));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }, String.valueOf(i)).start();
        }
    }

    // 解决方式三：将SimpleDateFormat定义成局部变量
    private static void sdfByNew() {
        for (int i = 1; i <= 5; i++) {
            new Thread(() -> {
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    System.out.println(sdf.parse("2022-06-01 11:11:11"));
                    sdf = null;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }, String.valueOf(i)).start();
        }
    }

    private static void sdfByThreadLocal() {
        for (int i = 1; i <= 5; i++) {
            new Thread(() -> {
                try {
                    System.out.println(DateUtilsDemo.parseByThreadLocal("2022-06-01 11:11:11"));
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    sdfThreadLocal.remove();
                }
            }, String.valueOf(i)).start();
        }
    }
}
